package com.banksoft.front.controller;

import com.banksoft.admin.SystemCache;
import com.banksoft.admin.bean.Enable;
import com.banksoft.admin.bean.MemberType;
import com.banksoft.admin.dao.UserDao;
import com.banksoft.admin.entity.Dictionary;
import com.banksoft.admin.entity.Order;
import com.banksoft.admin.entity.User;
import com.banksoft.admin.service.BaseService;
import com.banksoft.admin.service.DictionaryService;
import com.banksoft.admin.service.OrderService;
import com.banksoft.admin.service.UserService;
import com.banksoft.common.BaseController;
import com.banksoft.common.ConfigHelper;
import com.banksoft.front.bean.QrBack;
import com.banksoft.front.bean.WeiXinUser;
import com.banksoft.front.util.ImageDrawUtil;
import com.banksoft.front.util.WxSupportUtil;
import com.banksoft.util.*;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * Created by vanjoger on 2017/1/7.
 */
@Controller
@RequestMapping("/front/user")
public class FrontCenterController extends BaseController{

    @Autowired
    UserService userService;
    @Autowired
    OrderService orderService;
    @Autowired
    BaseService baseService;
    @Autowired
    DictionaryService dictionaryService;

    @RequestMapping("/checkShare")
    @ResponseBody
    public JSONObject checkShare(HttpServletRequest request){
        try{
          /*  String openId = getCookie(SystemCache.SESSION_USER, request);
            User user  = this.userService.findByOpenId(openId);*/
            User user = (User) request.getSession().getAttribute(SystemCache.SESSION_USER);
            if(user!=null){
                if(Enable.Yes.name().equals(user.getIsShare())){
                    return this.FmtResult(true,"",null);
                }else{
                    return this.FmtResult(false,"您还没有分享，请先分享！","2");
                }
            }
            return this.FmtResult(false,"没有找到您的信息","1");
        }catch (Exception e){
            e.printStackTrace();
            return this.FmtResult(false,"没有找到您的凭证信息","1");
        }
    }


    @RequestMapping("/toCenter")
    @ResponseBody
    public JSONObject toCenter(HttpServletRequest request){
        try {
            User user = (User) request.getSession().getAttribute(SystemCache.SESSION_USER);
            if(user!=null){
                /*List<Order> list = this.orderService.listByUserOpenId(user.getOpenId());
                if(StringUtil.isNotEmpty(list)){
                    return this.FmtResult(true,"",null);
                }else{
                    return this.FmtResult(false,"您还没有下单，下单后登录个人中心！","2");
                }*/
                return this.FmtResult(true,"",null);
            }
            return this.FmtResult(false,"没有找到您的信息","1");
        }catch (Exception e){
            e.getMessage();
            return this.FmtResult(false,"没有找到您的凭证信息","1");
        }

    }

    /**
     * 记录分享
     * @param request
     * @return
     */
    @RequestMapping("/share")
    @ResponseBody
    public JSONObject share(HttpServletRequest request, HttpServletResponse response){
        try {
          /*  String openId = getCookie(SystemCache.SESSION_USER, request);
            User user  = this.userService.findByOpenId(openId);*/
            User user = (User) request.getSession().getAttribute(SystemCache.SESSION_USER);
            if(user!=null){
                user.setIsShare(Enable.Yes.name());
/*
                String filePath = ConfigHelper.GetInstance().GetConfig("Upload_Path") + "/qrcode/" + DateUtil.getFormatDate(new Date(), "yyyyMMdd") + "/" + System.currentTimeMillis() + ".png";
                String file = getFilePath(filePath, request);

                String domain = getDomain(request);
                String url = domain+"/wx/index?state="+openId;
                QrCodeUtil.encodeQrCodeToFile(url,file);
                user.setImg(filePath);*/
                this.baseService.update(UserDao.class,user);
                return this.FmtResult(true,null,null);
            }
            return this.FmtResult(false,"",null);
        }catch (Exception e){
            e.getMessage();
        }
        return this.FmtResult(false,"",null);
    }

    @RequestMapping("dlzc")
    public String dlzc(Model model){
        List<Dictionary> list = dictionaryService.findByType("dlzc");
        if(StringUtil.isNotEmpty(list)){
            model.addAttribute("data",list.get(0));
        }
        return "front/dlzc";
    }

    @RequestMapping("cjwt")
    public String cjwt(Model model){
        List<Dictionary> list = dictionaryService.findByType("cjwt");
        if(StringUtil.isNotEmpty(list)){
            model.addAttribute("data",list.get(0));
        }
        return "front/cjwt";
    }

    @RequestMapping("/toQrCode")
    @ResponseBody
    public JSONObject toQrCode(HttpServletRequest request){
        try{
            User user = (User) request.getSession().getAttribute(SystemCache.SESSION_USER);
            if(user!=null) {
                if(MemberType.Customer.name().equals(user.getType())) {
                    List<Order> list = this.orderService.listByUserIds(new String[]{user.getId()});
                    if (StringUtil.isNotEmpty(list)) {
                        return this.FmtResult(true, "", null);
                    } else {
                        return this.FmtResult(false, "您还没有下单，下单后才能查看我的二维码！", null);
                    }
                }else{
                    return this.FmtResult(true,null,null);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return this.FmtResult(false,"当前无法查看个人二维码",null);
    }

    @RequestMapping("/myqrCode")
    public String myqrCode(HttpServletRequest request, Model model){
        User user = (User) request.getSession().getAttribute(SystemCache.SESSION_USER);
        if(user!=null){
            try {
                String qrCodeImg = "";
                QrBack qrBack = WxSupportUtil.qr(SystemCache.getWxSetting(),user.getId());
                if(qrBack!=null)
                     qrCodeImg = generalImg(user,qrBack.getUrl(),request);

                String path =  request.getSession().getServletContext().getRealPath("/");
                String baseImg = path + "/resources/images/fx.jpg";
                String downPath = path+"/upload/qrcode/" + DateUtil.getFormatDate(new Date(), "yyyyMMdd") + "/";

                String fileName = "/upload/qrcode/" + DateUtil.getFormatDate(new Date(), "yyyyMMdd") + "/"+System.currentTimeMillis() + ".png";
                String dstFile = path+ fileName;

                File file = new File(baseImg);
                File dFile = new File(dstFile);
                //先复制模板文件
                FileUtil.copyFile(file,dFile);
                System.out.println("qrcodeImg : "+qrCodeImg);
                System.out.println("dstFile : "+dstFile);
                ImageDrawUtil.pressImage(path+qrCodeImg,dstFile,220,420);

                if(!StringUtil.isNotNull(user.getHeadimgUrl())||(StringUtil.isNotNull(user.getHeadimgUrl())&&!user.getHeadimgUrl().startsWith("http://"))){//有时候头像没有加载出来 重新获取一遍
                    try {
                        WeiXinUser weiXinUser = WxSupportUtil.getWeiXinUser(user.getOpenId(), SystemCache.getWxSetting());
                        user.setNickName(weiXinUser.getNickname());
                        user.setSex(weiXinUser.getSex());
                        user.setCountry(weiXinUser.getCountry());
                        user.setProvince(weiXinUser.getProvince());
                        user.setHeadimgUrl(weiXinUser.getHeadimgurl());
                        user.setCity(weiXinUser.getCity());
                        this.baseService.update(UserDao.class,user);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if(StringUtil.isNotNull(user.getHeadimgUrl())&&user.getHeadimgUrl().startsWith("http://")){
                    //下载远程图片到本地
                    String localFile = System.currentTimeMillis()+".png";
                    HttpUrlConnection.download(user.getHeadimgUrl(),localFile,downPath);

                    String tfile = downPath+localFile;

                    String newFile = FileUtil.zipImageFile(tfile,150,150,1,"");

                    ImageDrawUtil.pressImage(newFile,dstFile,250,90);
                }else{

                    String img = path + "/resources/images/noavatar.gif";
                    String newFile = FileUtil.zipImageFile(img,150,150,1,"");

                    ImageDrawUtil.pressImage(newFile,dstFile,250,90);
                }

                model.addAttribute("img",fileName);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return "front/my_code";
    }


    /**
     * 生成二维码图片
     * @param user
     * @param request
     */
    private String generalImg(User user,String content,HttpServletRequest request) {
            String filePath = ConfigHelper.GetInstance().GetConfig("Upload_Path") + "/qrcode/" + DateUtil.getFormatDate(new Date(), "yyyyMMdd") + "/" + System.currentTimeMillis() + ".png";
            String file = getFilePath(filePath, request);
            try {
                QrCodeUtil.encodeQrCodeToFile(content, file);
                user.setImg(filePath);
                this.baseService.update(UserDao.class, user);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return filePath;
    }
}
